{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Exercício 1 - Centralidade\n",
    "\n",
    "Nesse exercício iremos importar, gerar e comparar a centralidade de 2 grafos: \n",
    "- Um pedaço da rede do facebook, coletado dos participantes de um survey que usaram o aplicativo [Social Circles](https://www.facebook.com/apps/application.php?id=201704403232744) no Facebook ([link para o dataset](http://snap.stanford.edu/data/egonets-Facebook.html)).\n",
    "- Um grafo randômico com a mesma quantidade de nós e de arestas."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import network_analysis_utils as nau\n",
    "import networkx as nx\n",
    "\n",
    "# Available functions:\n",
    "#\n",
    "#  - nau.facebook_nx_graph(): Obtém o grafo Networkx do facebook\n",
    "#  \n",
    "#  - nau.random_nx_graph(): Obtém o grafo Networkx randômico\n",
    "#  \n",
    "#  - nau.write_btwns_graph(nx_graph, weight_dict, output_filename): \n",
    "#      Plota o grafo em um arquivo de acordo com o dicionário de pessos obtidos do \"betwenness centrality\"\n",
    "#\n",
    "# Obs: o prefixo 'nx' indica o uso da Networkx, a lib de grafos utilizada nesse exercício"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Agora você deve escrever a sua função que computa a _betweenness centrality_ para um grafo nx:\n",
    "\n",
    "> __Dica__: recomendo fortemente o uso da [all_shortest_paths](http://networkx.readthedocs.io/en/networkx-1.11/reference/generated/networkx.algorithms.shortest_paths.generic.all_shortest_paths.html) da Networkx\n",
    "\n",
    "> __Requisito__: Não vale usar a [função de betweenness centrality do networkx](http://networkx.readthedocs.io/en/networkx-1.11/reference/generated/networkx.algorithms.centrality.betweenness_centrality.html)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# ALGORITHM: Betweenness Centrality\n",
    "# INPUT: G(V, E)\n",
    "# OUTPUT: Dictionary(V, Weights)\n",
    "#\n",
    "# BEGIN\n",
    "#   result <- init_empty_betweenness(V)\n",
    "# \n",
    "#   FOR EACH vi, vj in V THEN\n",
    "# \n",
    "#     IF vi < vj THEN\n",
    "#     \n",
    "#       shortest_paths <- get_shortest_paths(G, vi, vj)\n",
    "#     \n",
    "#       contribuition <- 1 / SIZE_OF(shortest_paths)\n",
    "#\n",
    "#       FOR EACH path IN shortest_paths THEN\n",
    "#       \n",
    "#         FOR EACH pi IN path IF pi != vi AND pi != pj\n",
    "#       \n",
    "#           result[pi] += contribuition\n",
    "#\n",
    "# RETURN result\n",
    "# END\n",
    "\n",
    "def betweenness_centrality(nx_graph):\n",
    "    \"\"\" Return the weight dictionary {node: betweenness centrality} \"\"\"\n",
    "    \n",
    "    nodes = nx_graph.nodes()\n",
    "    edges = nx_graph.edges()\n",
    "    btwns_dict = { node: 0.0 for node in nodes }\n",
    "    \n",
    "    for node in nodes:\n",
    "        for other in nodes:\n",
    "            if (node < other): # don't double count\n",
    "                paths = [p for p in nx.all_shortest_paths(nx_graph, node, other)]\n",
    "                contrib = 1.0 / len(paths)\n",
    "                for path in paths:\n",
    "                    for n in path:\n",
    "                        if n not in [node, other]:\n",
    "                            btwns_dict[n] += contrib\n",
    "    \n",
    "    return btwns_dict"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Agora que temos nossa função de centralidade pronta, podemos obter a centralidades para os dois gráficos:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "facebook_graph = nau.facebook_nx_graph()\n",
    "random_graph = nau.random_nx_grap()\n",
    "\n",
    "facebook_btwns = betweenness_centrality(facebook_graph)\n",
    "random_btwns = betweenness_centrality(random_graph)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "E agora geraremos os gráficos dos grafos para análise visual:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "nau.write_btwns_graph(facebook_graph, facebook_btwns, 'facebook_btwns_graph.png')\n",
    "nau.write_btwns_graph(random_graph, random_btwns, 'random_btwns_graph.png')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Agora abra os dois arquivos gerados: __facebook_btwns_graph.png__ e __random_btwns_graph.png__ e analise a distribuição da centralidade."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
